package com.xiaolin.controller;

import com.xiaolin.pojo.Message;
import com.xiaolin.pojo.MessageContext;
import com.xiaolin.pojo.User;
import com.xiaolin.pojo.vo.BaseResult;
import com.xiaolin.pojo.vo.WsMessage;
import com.xiaolin.service.MessageContextService;
import com.xiaolin.service.MessageService;
import com.xiaolin.utils.CommonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author XiaoLin
 * @date 2019/2/25 11:41
 */
@RestController
@RequestMapping("/mc")
public class MessageContextController {

    @Autowired
    private MessageContextService messageContextService;

    @Autowired
    private MessageService messageService;

    /**
     * Spring WebSocket消息发送模板
     */
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 发送聊天信息
     *
     * @param mc
     * @return
     */
    @PostMapping("/sendMessage")
    public ResponseEntity<BaseResult> sendMessage(@RequestBody MessageContext mc, HttpServletRequest request) {

        try {
            //获取请求作用域中的user
            User user = (User) request.getAttribute("user");
            //判断是否存在聊天对象
            Message message = messageService.findMessageByUIdAndRid(user.getUid(), mc.getReceiveUid());

            //判断是否有聊天对象
            if (message == null) {
                //不存在则新建一个聊天对象
                message = new Message();
                message.setSendUid(user.getUid());
                message.setReceiveUid(mc.getReceiveUid());
                //保存聊天对象
                messageService.insert(message);
            }
            //记录时间
            mc.setSendDate(new Date());
            //标记未读
            mc.setViewState(1);
            mc.setMid(message.getMid());

            //保存聊天信息
            messageContextService.sendMC(mc);
            //更新最后回复时间
            messageService.upLastDate(mc.getMid());

            message = messageService.findMessageByMid(message.getMid());

            // 推送聊天信息
            messagingTemplate.convertAndSendToUser(mc.getReceiveUid(), "/queue/msg/new", new WsMessage(1, message));
            //回调信息
            return ResponseEntity.ok(new BaseResult(0, "发送成功!", message));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(new BaseResult(1, "发送失败!"));
    }

    /**
     * 更新未读消息为已读
     *
     * @param mid
     * @param request
     * @return
     */
    @PutMapping("/upNotRead/{mid}")
    public ResponseEntity<BaseResult> upNotRead(@PathVariable Integer mid, HttpServletRequest request) {
        try {
            String uid = (String) request.getAttribute("userId");
            messageContextService.upNotReadByMid(mid, uid);
            return ResponseEntity.ok(new BaseResult(0, "更新成功!"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(new BaseResult(1, "更新失败!"));
    }


    /**
     * 发送文件
     *
     * @return
     */
    @PostMapping("/sendFile")
    public ResponseEntity<BaseResult> sendFile(@RequestParam("file") MultipartFile file, @RequestParam("type") String type, HttpServletRequest request) {

        try {
            String uid = (String) request.getAttribute("userId");
            String fileName = file.getOriginalFilename();
            //文件后缀名

            String suffix;
            if (fileName.lastIndexOf(".") != -1) {
                suffix = fileName.substring(+1);
                //"bmp gif jpg jpeg jpe png".indexOf(suffix) != -1
                if (suffix.equals("bmp") || suffix.equals("gif") || suffix.equals("jpg") ||
                        suffix.equals("jpeg") || suffix.equals("png")) {
                    type = "image";
                }
            } else {
                suffix = null;
            }

            String path;
            if ("image".equals(type)) {
                path = "\\" + type + "\\" + uid + "_" + UUID.randomUUID().toString() + (suffix == null ? "" : "." + suffix);
            } else {
                path = "\\" + type + "\\" + UUID.randomUUID().toString() + "\\" + fileName;
            }
            //保存文件
            String name = CommonData.filePath + path;
            File file1 = new File(name);
            File fileParent = file1.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file1));
            out.write(file.getBytes());
            out.flush();
            out.close();

            return ResponseEntity.ok(new BaseResult(0, "发送成功!", CommonData.imgServerUrl + path));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(new BaseResult(1, "发送失败!"));
    }

}
